package ubadbtools.deadlockAnalyzer.scheduleRecords;

import java.sql.Timestamp;

import ubadbtools.deadlockAnalyzer.database.Database;
import ubadbtools.deadlockAnalyzer.exceptions.InvalidPreconditionException;
import ubadbtools.deadlockAnalyzer.exceptions.TransitionException;
import ubadbtools.deadlockAnalyzer.transactions.TRX;
import ubadbtools.deadlockAnalyzer.transactions.TRXState;


public class RequestLockRecord extends ScheduleRecord
{
	private String 	item;
	
	
	public RequestLockRecord(String transaction, String item)
	{
		this.transaction = transaction;
		this.item = item;
	}
	
	public String getItem()
	{
		return item;
	}

	public String toString()
	{
		return "REQUEST_LOCK(" + item + ")"; 
	}
	
	
	protected boolean okPrecondition() {
		return ! getTRX().isRequested(item) && ! getTRX().isLocked(item);
	}
	
	protected void setPoscondition() {
		getTRX().addRequested(item);
		
		Database db = Database.getInstance();
		TRX trx = db.getTRXForLockedItem(item);
		if (trx != null) {
			getTRX().wait(trx, item);
		}
	}

	protected TRXState getNextTRXState() throws TransitionException {
		return getTRX().getTRXState().requestlock();
	}
	
	public void validarPrevencion() throws TransitionException,InvalidPreconditionException {
 
		   Database db = Database.getInstance();
		   
			TRX trx = db.getTRXForLockedItem(item);
			if (trx != null) {
				Timestamp timestamp =  getTRX().getTimestamp();
				Timestamp timestampOtraTRX = trx.getTimestamp();
				if (timestamp.after(timestampOtraTRX)){
					TRXState next = getTRX().getTRXState().abort();
					getTRX().setTRXState(next);
					getTRX().cleanup();		
					throw new InvalidPreconditionException("La transaccion posee menor prioridad de la necesaria para realizar el paso indicado.\n La transaccion sera abortada.");			
				}
			}
		
		}
	
}
